package br.uvv.sao.util;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import br.uvv.sao.domain.Usuario;
import br.uvv.sao.managedBean.ContextoBean;
import br.uvv.sao.managedBean.LoginBean;

public class Util {
	public static String gerarSenha(){
		String senha = "";
		int random;
		boolean v = false;

		for(int i = 0; i<10; i++) {
			v = false;
		
			do {
				random = (int) (Math.random() * 122);
				
				if (random >= 48 && random <= 57)
					v = true;
				else if (random >= 97 && random <= 122)
					v = true;
				else if (random >= 65 && random <= 90)
					v = true;
			} while (!v);
			
			senha += ((char) random);
		}
		return senha;
	}
	
	public static void redirecionar(String destino){
		FacesContext ctx = FacesContext.getCurrentInstance();
        ExternalContext extContext = ctx.getExternalContext();
        String url = extContext.encodeActionURL(ctx.getApplication().getViewHandler().getActionURL(ctx, destino));
        try {
            extContext.redirect(url);
        } catch (IOException ioe) {
            throw new FacesException(ioe);
		}
	}
	
	public static Object capturaBean(String nomeBean){
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
	    HttpSession session = ((HttpServletRequest)request).getSession();
	    return session.getAttribute(nomeBean);
	}
	
	public static Usuario getUsuarioLogado(){
		try {
			LoginBean contexto = (LoginBean) capturaBean("loginBean");
			return contexto.getUsuarioInstance();
		} catch (Exception e){
			System.out.println("Erro ao pegar o usuário logado: " + e.getCause());
		}
		return null;
	}
	
	public static void setDataTableRows(Integer rows){
		try {
			ContextoBean bean = (ContextoBean) Util.capturaBean("contextoBean");
		    if(bean!=null){ bean.setDataTableRows(rows); }
		} catch (NullPointerException e) {}
	}
}
